<template>
  <VDialog @close="handleClose" @save="save" :loading="loading" width="720">
    <template #content>
      <div>
        <el-form
          label-position="top"
          ref="formRef"
          :model="formValues"
          :rules="rules"
        >
          <el-form-item label="付款渠道" prop="accountType">
            <VGroup class="w-[100%]">
              <VSelects
                v-model="formValues.accountType"
                :dataSourse="optionsData?.account_type || []"
                placeholder="类型"
                @change="handleAccountType"
              />
              <VSelects
                v-model="formValues.accountChannelId"
                :dataSourse="optionsData?.channelList || []"
                placeholder="渠道/银行名称"
                class="w-[100%]"
                labelField="channelName"
                valueField="id"
                @change="handleAccountChanne"
              />
            </VGroup>
          </el-form-item>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="付款账号" prop="accountId">
                <VSelects
                  v-model="formValues.accountId"
                  :dataSourse="accountOption"
                  placeholder="请选择卡号"
                  class="w-[100%]"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="付款主体" prop="principalId">
                <VSelects
                  v-model="formValues.principalId"
                  :dataSourse="optionsData?.principalIds || []"
                  placeholder="请选择"
                  class="w-[100%]"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item prop="currency">
                <template #label>
                  <div>
                    <span class="font-bold">付款金额</span>
                    <span class="mx-[8px]">人民币: ¥{{ total }}</span>
                    <span>汇率: {{ formValues.exchangeRate }}</span>
                  </div>
                </template>
                <VGroup>
                  <el-input-number
                    v-model.trim="formValues.amount"
                    clearable
                    :controls="false"
                    placeholder="请输入"
                    class="w-[100%]"
                    @input="handleAmount"
                  />
                  <VSelects
                    v-model="formValues.currency"
                    :dataSourse="optionsData?.currency || []"
                    placeholder="请选择"
                    class="w-[200px]"
                    @change="handleCurrency"
                    valueField="label"
                  />
                </VGroup>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="付款时间">
                <el-date-picker
                  v-model="formValues.paymentAt"
                  type="datetime"
                  :disabled-date="disabledDate"
                  placeholder="选择日期"
                  class="w-[100%]"
                  value-format="YYYY-MM-DD HH:mm:ss"
                ></el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="资金项目" prop="fundUse">
                <VSelects
                  v-model="formValues.fundUse"
                  :dataSourse="optionsData?.payment_fund_use || []"
                  placeholder="请选择"
                  class="w-[100%]"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="业务部门">
                <VCascader
                  key="2"
                  v-model="formValues.departmentId"
                  collapse-tags
                  :multiple="false"
                  type="1"
                  class="w-[100%]"
                  placeholder="请选择"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="资金说明">
            <el-input
              v-model="formValues.illustrate"
              :rows="2"
              type="textarea"
            />
          </el-form-item>
          <el-form-item label="备注">
            <el-input v-model="formValues.remark" :rows="2" type="textarea" />
          </el-form-item>
        </el-form>
      </div>
    </template>
  </VDialog>
</template>
<script setup>
import { ElMessage } from "element-plus";
import { isDateInRange, getCurrentDate } from "@/utils/time.js";
import { updatePayment, addPayment } from "../../../api";
import { getAccountOption } from "@/api/index.js";
import { performOperation } from "@/utils/currencyHelper.js";
const props = defineProps({
  data: { type: Object, default: () => {} },
  optionsData: { type: Object, default: () => {} },
});
const { optionsData } = toRefs(props);
const rules = reactive({
  accountType: [{ required: true, message: "付款渠道", trigger: "change" }],
  accountId: [{ required: true, message: "付款账号", trigger: "change" }],
  principalId: [{ required: true, message: "付款主体", trigger: "change" }],
  amount: [{ required: true, message: "付款金额", trigger: "blur" }],
  fundUse: [{ required: true, message: "资金项目", trigger: "change" }],
});
const emit = defineEmits(["update:modelValue", "close", "refresh"]);
const loading = ref(false);
const formValues = ref({
  id: null,
  accountType: null,
  accountChannelId: null,
  accountId: null,
  principalId: null,
  amount: null,
  currency: "CNY",
  exchangeRate: 1.0,
  paymentAt: null,
  fundUse: null,
  departmentId: null,
  illustrate: null,
  remark: null,
});
const formRef = ref();
watch(
  () => props.data,
  (val) => {
    if (val) {
      for (let key in formValues.value) {
        formValues.value[key] = val[key];
      }
      if (formValues.value.id) {
        getAccountOptionList({
          accountChannelId: formValues.value.accountChannelId,
          accountType: formValues.value.accountType,
        });
        total.value = performOperation(
          "multiply",
          formValues.value.amount,
          formValues.value.exchangeRate
        );
      }
    }
  }
);
const disabledDate = (time) => {
  return !isDateInRange(time);
};
const save = async () => {
  await formRef.value.validate(async (valid, fields) => {
    if (!formValues.value?.accountChannelId) {
      ElMessage.warning("渠道/银行名称不能为空!");
    }
    if (!formValues.value?.amount) {
      ElMessage.warning("付款金额不能为空!");
    }
    if (valid) {
      try {
        loading.value = true;
        const { code, message } = await (formValues.value?.id
          ? updatePayment
          : addPayment)(formValues.value);
        if (code !== 200) return;
        ElMessage.success(formValues.value?.id ? "编辑成功" : "添加成功");
        handleClose(true);
      } catch (error) {
      } finally {
        loading.value = false;
      }
    }
  });
};
const accountOption = ref([]);
const handleAccountChanne = (val) => {
  if (!(val && formValues.value.accountType)) {
    formValues.value.accountId = null;
    accountOption.value = [];
    return;
  }
  getAccountOptionList({
    accountChannelId: val,
    accountType: formValues.value.accountType,
  });
};
const handleAccountType = (val) => {
  if (!(val && formValues.value.accountChannelId)) {
    formValues.value.accountId = null;
    accountOption.value = [];
    return;
  }
  getAccountOptionList({
    accountChannelId: formValues.value.accountChannelId,
    accountType: val,
  });
};
const getAccountOptionList = async (params) => {
  const { data } = await getAccountOption(params);
  data?.forEach((item) => {
    item.value = item.value.toString();
  });
  accountOption.value = data || [];
};
const total = ref(0);
const handleCurrency = (val) => {
  if (!val) return;
  let obj = optionsData?.value.currency.find((item) => item.label == val);
  if (obj) {
    formValues.value.exchangeRate = obj.value;
  } else {
    formValues.value.exchangeRate = 1.0;
  }
  if (val && formValues.value.amount) {
    total.value = performOperation(
      "multiply",
      formValues.value.amount,
      formValues.value.exchangeRate
    );
    // total.value = formValues.value.amount * formValues.value.exchangeRate;
  } else {
    total.value = 0;
  }
};
const handleAmount = (val) => {
  if (val && formValues.value.currency) {
    total.value = performOperation(
      "multiply",
      formValues.value.exchangeRate,
      val
    );
    // formValues.value.exchangeRate * val;
  } else {
    total.value = 0;
  }
};
const handleClose = async (refresh) => {
  formValues.value = {
    id: null,
    accountType: null,
    accountChannelId: null,
    accountId: null,
    principalId: null,
    amount: null,
    currency: "CNY",
    exchangeRate: 1.0,
    paymentAt: null,
    fundUse: null,
    departmentId: null,
    illustrate: null,
    remark: null,
  };
  formRef.value.resetFields();
  emit("update:modelValue", false);
  emit("close");
  if (refresh) emit("refresh");
};
</script>
